package com.sunshine.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sunshine.domain.Pay;
import com.sunshine.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/userpay")
public class PayController {
    @Autowired
    private PayService payService;


    @RequestMapping("/hello")
    public String hello() {
        return "hello sunshine";
    }

    @PostMapping("/pay")
    @SentinelResource(value = "pay", blockHandler = "handleBlock")
    public Map<String, Object> pay(Integer commodityId, Integer userId, Integer quantity) {

        return payService.pay(commodityId, userId, quantity);


    }
    
    /**
     * Sentinel限流处理方法
     * @param commodityId 商品ID
     * @param userId 用户ID
     * @param quantity 数量
     * @param ex 异常信息
     * @return 限流处理结果
     */
    public Map<String, Object> handleBlock(Integer commodityId, Integer userId, Integer quantity, BlockException ex) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "系统繁忙，请稍后重试");
        result.put("error", "FLOW_LIMITING");
        return result;
    }
}